package edu.hubu.book.controller;

import edu.hubu.book.domain.UserResultInfo;
import edu.hubu.book.domain.User;
import edu.hubu.book.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 用户web层（表现层）
 */
@Controller
@CrossOrigin(allowCredentials="true")
//@SessionAttributes(value = {"user"})
@RequestMapping("/user")
public class UserController {

    @Autowired private UserService userService;


    /**
     * 注册用户
     *
     * @return
     */
    @RequestMapping("/regist")
    public @ResponseBody UserResultInfo regist(User user, String check, ModelMap modelMap, HttpServletRequest request) {
        //从sesion中获取验证码
        //        String checkcode_server = (String) modelMap.get("CHECKCODE_SERVER");
        ////        sessionStatus.setComplete();
        //
        //        String checkcode_server = (String)session.getAttribute("CHECKCODE_SERVER");
        //        System.out.println("获取session中的验证码："+checkcode_server);
        //        session.removeAttribute("CHECKCODE_SERVER");
        //        String usersession1 = (String)session.getAttribute("CHECKCODE_SERVER");
        //        System.out.println("再次获取session中的验证码："+usersession1);
        //        System.out.println("注册用户：" + user);
        //        System.out.println("注册用户验证码：" + check);
        //        //比较
        //        if (checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)) {
        //            //验证码错误
        //            UserResultInfo info = new UserResultInfo();
        //            //注册失败
        //            info.setFlag(false);
        //            info.setErrorMsg("验证码错误,请点击刷新");
        //            return info;
        //        }

        //调用service完成注册
        HttpSession session = request.getSession();
        boolean flag = userService.regist(user);
        System.out.println("注册结果："+flag);
        UserResultInfo info = new UserResultInfo();
        //响应结果
        if (flag) {
            //注册成功
            info.setFlag(true);
        } else {
            //注册失败
            info.setFlag(false);
            info.setErrorMsg("用户名或邮箱已存在，注册失败!");
        }

        return info;
    }

    /**
     * 用户登录
     *
     * @return
     */
    @RequestMapping("/login")
    public @ResponseBody
    UserResultInfo login(User user, ModelMap modelMap, String check, SessionStatus sessionStatus, HttpServletRequest request) {
        //从sesion中获取验证码
        //        HttpSession session = request.getSession();
        //        String checkcode_server = (String) modelMap.get("CHECKCODE_SERVER");
        //        System.out.println(checkcode_server);
        //        String checkcode_server = (String)session.getAttribute("CHECKCODE_SERVER");
        //        System.out.println("获取session中的验证码："+checkcode_server);
        //        session.removeAttribute("CHECKCODE_SERVER");
        //        String usersession1 = (String)session.getAttribute("CHECKCODE_SERVER");
        //        System.out.println("再次获取session中的验证码："+usersession1);
        //        System.out.println("用户提交的验证码：" + check);

        //        //比较
        //        if (checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)) {
        //            //验证码错误
        //            UserResultInfo info = new UserResultInfo();
        //            //注册失败
        //            info.setFlag(false);
        //            info.setErrorMsg("验证码错误，请点击刷新");
        //            return info;
        //        }
        //调用Service查询
        HttpSession session = request.getSession();
        System.out.println(user);
        User u = userService.login(user);
        System.out.println(u);

        UserResultInfo info = new UserResultInfo();

        //判断用户对象是否为null
        if (u == null) {
            //用户名密码或错误
            info.setFlag(false);
            info.setErrorMsg("用户名密码或错误");
        }
        //判断用户是否激活
        if (u != null && !"Y".equals(u.getStatus())) {
            //用户尚未激活
            info.setFlag(false);
            info.setErrorMsg("您尚未激活，请激活");
        }
        //判断登录成功
        if (u != null && "Y".equals(u.getStatus())) {
            //            modelMap.addAttribute("user", u);//登录成功标记
            session.setAttribute("user", u);
            //登录成功
            info.setFlag(true);
            info.setErrorMsg("登录成功");
        }

        return info;
    }


    /**
     * 查询已经登录的用户信息
     */
    @RequestMapping("/findOne")
    public @ResponseBody UserResultInfo findOne(HttpServletRequest request) {
        HttpSession session = request.getSession();
        System.out.println(session);
        //从session中获取登录用户
        User user = (User) session.getAttribute("user");
        System.out.println(user);
        UserResultInfo info = new UserResultInfo();
        if (user == null){
            info.setErrorMsg("未登录");
            info.setFlag(false);
            return info;
        }
        info.setErrorMsg(user.getUsername());
        info.setFlag(true);
        return info;
    }


    /**
     * 验证码激活
     */
    @RequestMapping("/active")
    public void active(String code, HttpServletResponse response) throws Exception {
        if (code != null) {
            //调用service完成激活
            boolean flag = userService.active(code);
            String msg = null;
            if (flag) {
                //激活成功
                msg = "激活成功";
            } else {
                //激活失败
                msg = "激活失败，请联系管理员!";
            }
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(msg);
            return;
        }
        String msg = "激活失败，请联系管理员!";
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(msg);
    }

    /**
     * 用户退出
     */
    @RequestMapping("/exit")
    public @ResponseBody UserResultInfo exit(SessionStatus sessionStatus, HttpServletRequest request) {

        HttpSession session = request.getSession();

        User user1 = (User) session.getAttribute("user");
        System.out.println(user1);

        //1.销毁session
        //        sessionStatus.setComplete();
        session.removeAttribute("user");
        User user2 = (User) session.getAttribute("user");
        System.out.println(user2 + "清除后");

        UserResultInfo info = new UserResultInfo();
        info.setFlag(true);
        info.setErrorMsg("退出成功");

        //2.跳转登录页面
        return info;

    }


    /**
     * 验证码图片的绘制并返回
     *
     * @param request
     * @param response
     * @param session
     */
    @RequestMapping("/codepaint")
    public void codepaint(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        //服务器通知浏览器不要缓存
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-control", "no-cache");
        response.setHeader("expires", "0");

        //在内存中创建一个长80，宽30的图片，默认黑色背景
        //参数一：长
        //参数二：宽
        //参数三：颜色
        int width = 80;
        int height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //获取画笔
        Graphics g = image.getGraphics();
        //设置画笔颜色为灰色
        g.setColor(Color.GRAY);
        //填充图片
        g.fillRect(0, 0, width, height);

        //产生4个随机验证码，12Ey
        String base = "0123456789ABCDEFGabcdefg";
        int size = base.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 1; i <= 4; i++) {
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        String checkCode = sb.toString();
        System.out.println(checkCode);
        session.setAttribute("CHECKCODE_SERVER", checkCode);
        String checkcode_server = (String)session.getAttribute("CHECKCODE_SERVER");
        System.out.println(checkcode_server);
        //将验证码放入HttpSession中
        //        model.addAttribute("CHECKCODE_SERVER", checkCode);
        //设置画笔颜色为黄色
        g.setColor(Color.YELLOW);
        //设置字体的小大
        g.setFont(new Font("黑体", Font.BOLD, 24));
        //向图片上写入验证码
        g.drawString(checkCode, 15, 25);

        //将内存中的图片输出到浏览器
        ImageIO.write(image, "PNG", response.getOutputStream());

    }
}
